import { ref, onMounted, getCurrentInstance, watch } from 'vue'
import {ElAutocomplete, ElIcon} from "../lib/element-plus@2.8.4/index.full.min.mjs";
import {Search} from "../lib/@element-plus/icons-vue@2.3.1/index.js";

const inChina = true
const cesiumToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiZjBmMDE4Ny05M2JlLTRlMzgtYjIxYi05YmJjM2QwMzJkYWMiLCJpZCI6MjU5LCJpYXQiOjE3MzA0NjY3MDl9.t-7gCGPUe-oGCyCoeXPtYmlMVdgqUQD9mn-Da23yUoI'

function fetchGeoList(queryText, cb) {
  const geoUrl = `https://api.cesium.com/v1/geocode/autocomplete?text=${queryText}&access_token=${cesiumToken}`
  fetch(geoUrl, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  }).then(res => {
    if (res.ok) {
      return res.json()
    } else {
      throw new Error('test fetch cesium geocode error')
    }
  }).then(json => {
    const results = []
    // console.log('fetchGeoList: ', json)
    json.features.forEach(it => {
      const [west, south, east, north] = it.bbox
      const longitude = (west + east) * 0.5
      const latitude = (south + north) * 0.5
      const pos = ` => ${longitude.toFixed(8)}°, ${latitude.toFixed(8)}°`
      results.push({value: it.properties.label + pos, bbox: it.bbox})
    })
    cb(results)
  })
}

// 使用天地图 进行 地理编码查询
// specifyCode: 城市国标码 / 	省国标码
async function queryGeocodeTianDiTu(queryText, output = [], specifyCode = -1) {
  const tianDiTuTk = '254a86978efe81b7e7523fe3321fbbae'
  const param = {
    "queryType":"1",
    "start":0,
    "mapBound":"61.1796875,0.05793129855838686,149.07031250000034,53.66180987844831",
    // "yingjiType":0,
    // "queryTerminal":10000,
    "level":3,
    "keyWord": queryText,
    "count":10,
    // "sourceType":0,
    // "specify":156420500
  }
  let fromSpecify = false
  if (specifyCode > 0) {
    param.specify = specifyCode
    fromSpecify = true
  }
  const geoUrl = `https://api.tianditu.gov.cn/v2/search?type=query&postStr=${JSON.stringify(param)}&tk=${tianDiTuTk}`
  const results = []
  const res = await fetch(geoUrl, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  })
  if (res.ok) {
    const json = await res.json()
    if (json.pois) {
      const infos = json.pois.map(it => {
        return {name: it.name, lonlat: it.lonlat, address: it.address}
      })
      output.push(...infos)
      // console.log('查询天地图: ', output)
      output.forEach(it => {
        results.push({value: it.address + '-' + it.name, lonlat: it.lonlat})
      })
      return Promise.resolve(output)
    } else if (json.statistics && json.statistics.priorityCitys) {
      const promiseArr = []
      json.statistics.priorityCitys.forEach(item => {
        const pro = queryGeocodeTianDiTu(queryText, output, item.adminCode)
        promiseArr.push(pro)
      })
      const output2 = await Promise.all(promiseArr)
      // return Promise.resolve(output2)
      return Promise.resolve(output)
    } else {
      return Promise.resolve(output)
    }
    console.log('Geocode TianDiTu: ', json)
  } else {
    return Promise.resolve([])
  }

}
// queryGeocodeTianDiTu('湖北龙潭河大桥')

export default {
  components: {
    ElAutocomplete, ElIcon, Search
  },
  setup(props, ctx) {
    onMounted(() => {})
    const geoInput = ref('')
    const handleSelect = (item) => {
      console.log('handleSelect', item)
    }
    const handleIconClick = (ev) => {
      console.log('handleIconClick', geoInput.value)
    }
    const  querySearch = async (queryString, cb) => {
      if (inChina) {
        const output = await queryGeocodeTianDiTu(queryString)
        const results = []
        output.forEach(it => {
          results.push({value: it.address + '-' + it.name, lonlat: it.lonlat})
        })
        cb(results)
      } else {
        fetchGeoList(queryString, cb)
      }
    }
    return {
      querySearch,
      handleSelect,
      handleIconClick,
      geoInput,
    }
  },
  template: `
  <div class="w-360">
    <el-autocomplete
      v-model="geoInput"
      :fetch-suggestions="querySearch"
      :trigger-on-focus="false"
      clearable
      class="inline-input"
      placeholder="Please Input"
      @select="handleSelect"
    >
      <template #suffix>
        <el-icon class="el-input__icon hand" @click="handleIconClick">
          <search />
        </el-icon>
      </template>
    </el-autocomplete>
  </div>
  `
}
